// src/main/java/com/urbane/banner/CustomBannerPrinter.java
package com.urbane.banner;

import org.springframework.core.env.Environment;

import java.io.InputStream;
import java.io.PrintStream;

public class CustomBannerPrinter {

    private static final String RESET = "\u001B[0m";
    private static final String GREEN = "\u001B[32m";
    private static final String CYAN = "\u001B[36m";
    private static final String YELLOW = "\u001B[33m";

    public static void printBanner(Environment environment, PrintStream out) {
        try {
            String appName = environment.getProperty("spring.application.name", "Unknown-Service").toUpperCase();
            String asciiArt = generateAsciiArt(appName);

            String serverPort = environment.getProperty("server.port", "8080");
            String profiles = String.join(",", environment.getActiveProfiles());
            String version = environment.getProperty("info.app.version", "1.0.0");
            String gitCommit = environment.getProperty("git.commit.id.abbrev", "unknown");
            String springBootVersion = org.springframework.boot.SpringBootVersion.getVersion();
            String startTime = java.time.LocalDateTime.now()
                    .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String hostAddress = getHostAddress();
            String baseUrl = "http://" + hostAddress + ":" + serverPort;
            String healthUrl = baseUrl + "/actuator/health";
            String swaggerUrl = baseUrl + (isSwaggerV3(environment) ? "/swagger-ui/index.html" : "/swagger-ui.html");

            out.println(GREEN + "===============================================" + RESET);
            out.println(CYAN + asciiArt + RESET);
            out.println(GREEN + "===============================================" + RESET);
            out.println("  服务端口    : " + YELLOW + "🌐 " + serverPort + RESET);
            out.println("  服务IP      : " + CYAN + "📍 " + hostAddress + RESET);
            out.println("  激活环境    : " + GREEN + "🧪 " + (profiles.isEmpty() ? "default" : profiles) + RESET);
            out.println("  服务版本    : " + YELLOW + "🏷️  " + version + RESET);
            out.println("  Git提交     : " + CYAN + "📦 " + gitCommit + RESET);
            out.println("  Spring Boot : " + GREEN + "🌱 " + springBootVersion + RESET);
            out.println("  启动时间    : " + YELLOW + "🕙 " + startTime + RESET);
            out.println("  健康检查    : " + CYAN + "🩺 " + healthUrl + RESET);
            out.println("  Swagger文档 : " + GREEN + "📚 " + swaggerUrl + RESET);
            out.println(GREEN + "===============================================" + RESET);
        } catch (Exception e) {
            out.println("⚠️  横幅打印异常: " + e.getMessage());
        }
    }

    private static String generateAsciiArt(String text) {
        try {
            InputStream fontStream = CustomBannerPrinter.class.getResourceAsStream("/fonts/ANSI Shadow.flf");
            if (fontStream == null) {
                // fallback to standard
                fontStream = CustomBannerPrinter.class.getResourceAsStream("/fonts/Standard.flf");
            }
            return FigletUtil.convertOneLine(fontStream, text);
        } catch (Exception e) {
            return "🚀 " + text;
        }
    }

    private static boolean isSwaggerV3(Environment env) {
        return env.getProperty("springdoc.api-docs.enabled", Boolean.class, false) ||
                env.containsProperty("springdoc.swagger-ui.path");
    }

    private static String getHostAddress() {
        try {
            java.net.InetAddress addr = java.net.InetAddress.getLocalHost();
            if (!addr.isLoopbackAddress() && !addr.isAnyLocalAddress()) {
                return addr.getHostAddress();
            }
            // 尝试获取非 loopback 地址
            java.util.Enumeration<java.net.NetworkInterface> nets = java.net.NetworkInterface.getNetworkInterfaces();
            while (nets.hasMoreElements()) {
                java.net.NetworkInterface net = nets.nextElement();
                if (net.isUp() && !net.isLoopback()) {
                    java.util.Enumeration<java.net.InetAddress> addresses = net.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        java.net.InetAddress ip = addresses.nextElement();
                        if (ip instanceof java.net.Inet4Address && !ip.isLoopbackAddress()) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception ignored) {}
        return "127.0.0.1";
    }
}
